package cn.js189.uqc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.js189.common.constants.BSSUrlConstants;
import cn.js189.common.constants.Constant;
import cn.js189.common.constants.Constants;
import cn.js189.common.domain.*;
import cn.js189.common.enums.CodeEnum;
import cn.js189.common.util.CodeConvertUtil;
import cn.js189.common.util.HttpUtil;
import cn.js189.common.util.MainUtils;
import cn.js189.common.util.Utils;
import cn.js189.common.util.exception.BaseAppException;
import cn.js189.uqc.common.CheckServSpecByDevModel;
import cn.js189.uqc.domain.UpOcrFtpInfo;
import cn.js189.uqc.mapper.CheckInfoMapper;
import cn.js189.uqc.util.*;
import cn.js189.uqc.service.INocBillService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author yxl
 * @Date 2024/3/1
 */
@Service
@Slf4j
public class INocBillServiceImpl implements INocBillService {
    private static final Logger logger = LoggerFactory.getLogger(INocBillServiceImpl.class);

    @Resource
    private SmartBssSystemUtil smartBssSystemUtil;

    @Resource
    private CheckInfoMapper checkInfoMapper;

    private static Map<String, String> map = new HashMap<>();
    /** 企信3级地区ID与区号对照集合. */
    public static Map<String, String> areaCodeMap = new HashMap<>();

    /** 企信四地区ID与OSS对照集合. */
    public static Map<String, String> areaIdMap = new HashMap<>();

    private static final String CUST_SFTP_IP = "132.252.128.145";
    private static final int CUST_SFTP_PORT = 22;
    private static final String CUST_SFTP_USER = "cust";
    private static final String CUST_SFTP_PD = "oiS7w#bd!wGbs";
    String localFilePath1 = (this.getClass().getResource("/").getPath()).replace("classes", "");
    String localFilePath = localFilePath1.substring(0, localFilePath1.length()-1) + "upOcrFiles/";

    @Override
    public String addInvoiceInformation(String requestJson) {
        logger.debug("新增发票抬头信息addInvoiceInformation.request:{}",requestJson);
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            JSONObject headJson = JSON.parseObject(requestJson).getJSONObject("head");
            String areaCode = headJson.getString("areaCode");
            tranId = headJson.getString("tranId");
            ReqInfo reqInfo = BeanUtil.toBean(requestJson,ReqInfo.class);
            JSONObject body = reqInfo.getBody();

            //编号
            String id = body.getString("id");
            //短信号码
            String mobile = body.getString("mobile");
            //电子邮箱
            String eMail = body.getString("eMail");
            //自动推送 1:是   2：否
            String automaticPush = body.getString("automaticPush");
            //购买方名称
            String invoiceHeader = body.getString("invoiceHeader");
            //购买方纳税人识别号
            String buyerTaxPayerId = body.getString("buyerTaxPayerId");
            //购买方地址
            String buyerAddress = body.getString("buyerAddress");
            //购买方电话
            String buyerPhone = body.getString("buyerPhone");
            //购买方银行账号（开户行+银行账号）
            String bankAccount = body.getString("bankAccount");
            //用户登录号码 ；接入号
            String serialNumber = body.getString("serialNumber");
            //类别 11：宽带 12：手机等
            String prodClass = body.getString("prodClass");
            //本地网标识
            String lanId = StaticDataMappingUtil.getRegionByAreaCode(areaCode);
            //客户号码类型
            String accNbrType = body.getString("accNbrType");
            //客户编码
            String custId = smartBssSystemUtil.getOwnerCustIdByQryProdInst(serialNumber, "1", accNbrType, "N", headJson);

            JSONObject reqJson = new JSONObject();
            reqJson.put("id", id);
            reqJson.put("mobile", mobile);
            reqJson.put("eMail", eMail);
            reqJson.put("automaticPush", automaticPush);
            reqJson.put("invoiceHeader", invoiceHeader);
            reqJson.put("buyerTaxPayerId", buyerTaxPayerId);
            reqJson.put("buyerAddress", buyerAddress);
            reqJson.put("buyerPhone", buyerPhone);
            reqJson.put("bankAccount", bankAccount);
            reqJson.put("serialNumber", serialNumber);
            reqJson.put("prodClass", prodClass);
            reqJson.put("lanId", lanId);
            reqJson.put("custId", custId);

            Map<String,String> headMap = new HashMap<>();
            headMap.put("X-CTG-Province-ID", "8320000");//省份Id
            headMap.put("X-CTG-Lan-ID", lanId);//地市id
            String requestId = UUID.randomUUID().toString();
            headMap.put(Constants.X_CTG_REQUEST_ID, requestId);
            String result = HttpClientHelperForEop.postWithMNPWithHeader(BSSUrlConstants.INVOICE_INFORMATION_URL, reqJson.toString(),headMap);
            if(StringUtils.isBlank(result)) {
                Map<String,String> bodyMap = new HashMap<>();
                bodyMap.put(Constants.X_CTG_REQUEST_ID, requestId);
                response = BSSHelper.getErrInfo("02", "查询错误，集团返回空值!",bodyMap);
            }else{
                JSONObject resultJson = JSON.parseObject(result);
                resultJson.put(Constants.X_CTG_REQUEST_ID, requestId);
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, resultJson, "success", "00", responseJson);
            }
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }
        return response.toString();
    }

    @Override
    public String askUserSessionType(String requestJSON) {
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            ReqInfo reqInfo = BeanUtil.toBean(requestJSON,ReqInfo.class);
            JSONObject body = reqInfo.getBody();
            String mdn = body.getString("phoneNbr");
            String address ="132.224.219.102";
            String reqTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String messageID = reqTime + new Random().nextInt(10)+new Random().nextInt(10)
                    +new Random().nextInt(10)+new Random().nextInt(10)
                    +new Random().nextInt(10)+new Random().nextInt(10);
            String username ="js189";
            String secret ="Js189.cn";
            String password = StringUtils.upperCase(MD5Utils.mD5(username+secret+reqTime));
            JSONObject postJSON = new JSONObject();
            postJSON.put("Mdn",mdn);
            postJSON.put("Address", address);
            postJSON.put("ReqTime", reqTime);
            postJSON.put("Username", username);
            postJSON.put("Password", password);
            postJSON.put("MessageID", messageID);
            String url ="http://132.224.255.43:18080/Business/AskUserSessionType";//正式
            String rsp = HttpClientHelperForEop.postWithMNP(url, postJSON.toString(), 10000);
            response = Utils.builderResponse(rsp, responseHead, responseJson, tranId,"ResultCode","","ResultMsg");
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }finally{
            logger.debug("askUserSessionType end");
        }
        return response.toString();
    }

    @Override
    public String bussinessOcr(String request) {
        logger.debug("营业执照识别 bussinessOcr request:{}",request);
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            tranId = JSON.parseObject(request).getJSONObject("head").getString("tranId");
            ReqInfo reqInfo = BeanUtil.toBean(request,ReqInfo.class);
            JSONObject body = reqInfo.getBody();
            String channel = body.getString("channel");
            String imgvalue = body.getString("imgvalue");
            String plateType = body.getString("plateType");
            JSONArray keys = body.getJSONArray("keys");
            String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            String url = "http://openapi.telecomjs.com:80/eop/AISystem/Identify_Of_Business_license/v1/apis/1/bussiness-ocr:1.1@alpha.fixed";

            JSONObject requestJSON = new JSONObject();
            requestJSON.put("channel", channel);
            requestJSON.put("image_value", imgvalue);
            requestJSON.put("uuid", uuid);
            requestJSON.put("plate_type", plateType);
            requestJSON.put("keys", keys);
            String requestParam = requestJSON.toJSONString();
            logger.debug("营业执照识别 input: {}", requestParam);
            String result = HttpClientUtils.doPostJSONHttpsNewEOP(url, requestParam);
            logger.debug("营业执照识别  output: {}", result);

            if (!StringUtils.isEmpty(result)) {
                JSONObject resultJson = JSON.parseObject(result);
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, resultJson, "success", "00", responseJson);
            } else {
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, null, "内部接口返回空", "98", responseJson);
            }
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }
        return response.toString();
    }

    @Override
    public String callAdslOrLanOnline(String param) {
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //  获得接口号流水
        String tranId = "";
        String rsp = "";

        String url = URLPropertyUtil.getContextProperty("uqc_callAdslOrLanState_url");
        String[] args=url.split("\\:");

        try (SocketChannel channel= SocketChannel.open(new InetSocketAddress(args[0], MainUtils.getInt(args[1])));){

            JSONObject requestJSON = JSON.parseObject(param);

            JSONObject head = requestJSON.getJSONObject("head");
            JSONObject body = requestJSON.getJSONObject("body");
            tranId =  head.getString("tranId");
            String serviceType = body.getString("serviceType");
            String accNbr = body.getString(Constants.ACC_NBR);


            String inParam=serviceType + "|||21|||M01="+ accNbr+ "|||M03=201|||U97=1,9,13,14,18,19,20,21";

            //// 获得与客户端通信的信道

            //设置阻塞模式
            channel.configureBlocking(false);
            // 将字节转化为为UTF-8的字符串
            ByteBuffer writeBuffer=ByteBuffer.wrap(inParam.getBytes(StandardCharsets.UTF_8));
            //写出字符串
            channel.write(writeBuffer);

            JSONObject json = new JSONObject();
            int read = 0;
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            long socketTimeout=0;
            while ((read = channel.read(buffer)) != -1) {
                if (read == 0) {
                    Thread.sleep(100);
                    socketTimeout+=100;
                    if(socketTimeout >= 40000) {
                        rsp = CodeEnum.CT_60002.name();
                        break;
                    }
                } else{
                    buffer.flip();
                    byte[] array = new byte[read];
                    buffer.get(array);
                    String s = new String(array,"GB2312");
                    s=s.trim();
                    json = method1(s);
                    break;
                }
                buffer.clear();
            }
            logger.debug("adsl和lan宽带在线状态查询-22014 output :{}" , rsp);
            response = Utils.builderResponseForADSL(json.toString(), responseHead, responseJson, tranId,"调用成功");
        } catch (InterruptedException ie) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            logger.debug("adsl和lan宽带在线状态查询-22014",ie);
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            logger.debug("adsl和lan宽带在线状态查询-22014 Exception :{}" , e.getMessage());
        }
        return response.toString();
    }

    @Override
    public String checkInvoiceInformation(String requestJson) {
        logger.debug("查询发票抬头信息checkInvoiceInformation.request:{}",requestJson);
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            JSONObject headJson = JSON.parseObject(requestJson).getJSONObject("head");
            String areaCode = headJson.getString("areaCode");
            tranId = headJson.getString("tranId");
            ReqInfo reqInfo = BeanUtil.toBean(requestJson,ReqInfo.class);
            JSONObject body = reqInfo.getBody();

            String serialNumber = body.getString("serialNumber");
            String type = body.getString("type");
            String prodClass = body.getString("prodClass");
            String lanId = StaticDataMappingUtil.getRegionByAreaCode(areaCode);

            StringBuilder urlSb = new StringBuilder(BSSUrlConstants.INVOICE_INFORMATION_URL);
            //prodClass 12：手机
            urlSb.append("?serialNumber=").append(serialNumber).append("&lanId=").append(lanId)
                    .append("&type=").append(type).append("&prodClass=").append(prodClass);

            Map<String,String> headMap = new HashMap<>();
            headMap.put("X-CTG-Province-ID", "8320000");//省份Id
            headMap.put("X-CTG-Lan-ID", lanId);//地市id
            String requestId = UUID.randomUUID().toString();
            headMap.put(Constants.X_CTG_REQUEST_ID, requestId);
            String result = HttpClientHelperForEop.getWithDcoss(urlSb.toString(), headMap);

            if(StringUtils.isBlank(result)) {
                Map<String,String> bodyMap = new HashMap<>();
                bodyMap.put(Constants.X_CTG_REQUEST_ID, requestId);
                response = BSSHelper.getErrInfo("02", "查询错误，集团返回空值!",bodyMap);
            }else{
                JSONObject resultJson = JSON.parseObject(result);
                resultJson.put(Constants.X_CTG_REQUEST_ID, requestId);
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, resultJson, "success", "00", responseJson);
            }

        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }
        return response.toString();
    }

    @Override
    public String checkServSpecByDevModel(String request) {
        logger.debug("checkServSpecByDevModel request:{}",request);
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            ReqInfo reqInfo = BeanUtil.toBean(request,ReqInfo.class);
            JSONObject requestJson = JSON.parseObject(request);
            JSONObject head = requestJson.getJSONObject("head");
            JSONObject body = reqInfo.getBody();
            String areaCode2 = areaIdMap.get(areaCodeMap.get(head.getString("areaCode")));
            String servSpecId = body.getString("servSpecId");//CRM服务规格ID
            String terminalCode = body.getString("terminalCode"); //UIM卡号

            CheckServSpecByDevModel cssbdm = new CheckServSpecByDevModel(areaCode2, servSpecId, terminalCode);
            String requestParam =  cssbdm.generateContractRoot().toJSONString();

            logger.debug("UIM卡是否支持指定服务校验input: {}", requestParam);
            String result = HttpClientUtils.doPostJSONHttps(BSSUrlConstants.OSS3_CHECK_SERV_SPEC_BY_DEV_MODEL_URL, requestParam);
            logger.debug("UIM卡是否支持指定服务校验 output: {}", result);

            if (!StringUtils.isEmpty(result)) {
                JSONObject resultJson = JSON.parseObject(result);
                JSONObject respBody = resultJson.getJSONObject("resultObject");
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, respBody, "success", "00", responseJson);
            } else {
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, null, "内部接口返回空", "98", responseJson);
            }
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }
        return response.toString();
    }

    @Override
    public String getAutoCheckResult(String request) {
        logger.debug("NocBillImpl.getAutoCheckResult.request:{}",request);
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            JSONObject headJson = JSON.parseObject(request).getJSONObject("head");
            tranId = headJson.getString("tranId");
            ReqInfo reqInfo = BeanUtil.toBean(request,ReqInfo.class);
            JSONObject body = reqInfo.getBody();

            //天翼看家、全屋wifi dcoos地址
            String url = "http://jsjteop.telecomjs.com:8764/ida40/public/asip/webServiceTrans";

            JSONObject paramJson = new JSONObject();
            //方法名，传getAutoCheckResult即可
            paramJson.put("asipServiceName", "getAutoCheckResult");
            //检测id
            paramJson.put("sessionId", body.getString("sessionId"));
            logger.debug("NocBillImpl.getAutoCheckResult.paramJson={}",paramJson.toJSONString());
            String result = HttpClientHelperForEop.postWithMNP(url, paramJson.toString(),30000);
            logger.debug("NocBillImpl.getAutoCheckResult.result={}",result);
            if(!StringUtils.isBlank(result)) {
                JSONObject resultJson = JSON.parseObject(result);
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, resultJson, "success", "00", responseJson);
            }else{
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, null, "企信接口返回空", "01", responseJson);
            }
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }
        return response.toString();
    }

    @Override
    public String getCardInfoByNum(String request) {
        logger.debug("getCardInfoByNum request:{}",request);
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            ReqInfo reqInfo = BeanUtil.toBean(request,ReqInfo.class);
            JSONObject requestJson = JSON.parseObject(request);
            JSONObject head = requestJson.getJSONObject("head");
            JSONObject body = reqInfo.getBody();
            String accNbr = body.getString(Constants.ACC_NBR);//手机号码
            String areaCode = head.getString(Constant.AREACODE);//区号
            String areaId = StaticDataMappingUtil.getBssToDubAreaMap(StaticDataMappingUtil.getRegionByAreaCode(areaCode));
            JSONObject msgHead = new JSONObject();
            msgHead.put("uuid", UUID.randomUUID().toString().replace("-", ""));
            msgHead.put("sourceSystem", "电子渠道");
            msgHead.put("reqTime", new SimpleDateFormat("yyyyMMddHHmmss"));
            JSONObject msgBody = new JSONObject();
            msgBody.put("areaId", areaId);
            msgBody.put("numberNo", accNbr);
            JSONObject reqJson = new JSONObject();
            JSONObject messageRoot = new JSONObject();
            messageRoot.put("msgHead", msgHead);
            messageRoot.put("msgBody", msgBody);
            reqJson.put("messageRoot", messageRoot);
            logger.debug("getCardInfoByNum reqJson:{}",reqJson);
            String url = "http://jseop.telecomjs.com:18888/eop/oss/getCardInfoByNum?appkey=js_dzqd";
            String rsp = HttpClientHelperForEop.postWithMNP(url, reqJson.toString(),10000);
            logger.debug("getCardInfoByNum rsp:{}",rsp);
            if(!StringUtils.isEmpty(rsp)){
                JSONObject rspJSON = JSON.parseObject(rsp);
                if("1".equals(rspJSON.getJSONObject("msgHead").getString("rspCode"))){
                    return BSSHelper.getErrInfoWithNullResObj("00", "查询成功", rspJSON).toString();
                }else{
                    return BSSHelper.getErrInfoWithNullResObj("01", "查询失败", rspJSON).toString();
                }
            }else{
                return BSSHelper.getErrInfo("02", "调用OSS失败").toString();
            }
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }
    }

    @Override
    public String queryDevSN(String requestJSON1) {
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            ReqInfo reqInfo = BeanUtil.toBean(requestJSON1,ReqInfo.class);
            JSONObject body = reqInfo.getBody();
            String accNbr = body.getString(Constants.ACC_NBR);//宽带号等
            String accNbrType = body.getString("accNbrType");//类型
            String reqStr =
                    "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:com=\"http://com.linkage.ims\">"+
                            "<soapenv:Header/>"+
                            "<soapenv:Body>"+
                            "<com:process soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"+
                            "<xmlStr xsi:type=\"xsd:string\">"+
                            "<![CDATA[<Esb><Route><ServCode>queryDevSN</ServCode><Pvalue>0003</Pvalue></Route><XmlData><root><CmdID>"+UUID.randomUUID().toString()+"</CmdID><CmdType>CX_01</CmdType><ClientType>3</ClientType><Param><UserInfoType>"+accNbrType+"</UserInfoType><UserInfo>"+accNbr+"</UserInfo></Param></root></XmlData></Esb>]]>"+
                            "</xmlStr>"+
                            "</com:process>"+
                            "</soapenv:Body>"+
                            "</soapenv:Envelope>";
            String url ="http://132.228.198.145:8099/CSB/services/CsbService";//正式
            String rsp = HttpUtil.postWebServiceHttpProxy(url, reqStr, 10000, "N","gbk");
            rsp = rsp.replace("&gt;", ">").replace("&lt;", "<");
            JSONObject newRsp  = Utils.parseSoapXML(rsp,"soapenv:Envelope");
            JSONObject root = newRsp.getJSONObject("body").getJSONObject("processresponse").getJSONObject("processreturn").getJSONObject("root");
            response = Utils.builderResponse(root.toString(), responseHead, responseJson, tranId,"rstcode","","rstmsg");
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }finally{
            logger.debug("queryDevSN end");
        }
        return response.toString();
    }

    @Override
    public String queryOrderDetail(String requestJSON1) {
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            ReqInfo reqInfo = BeanUtil.toBean(requestJSON1,ReqInfo.class);
            JSONObject body = reqInfo.getBody();
            ReqHead head = reqInfo.getHead();
            String accNbr = body.getString(Constants.ACC_NBR);//接入号
            String areaCode = head.getAreaCode();//地区
            JSONObject reqJson = new JSONObject();
            reqJson.put("businessType", accNbr);
                reqJson.put("localNetwork", CodeConvertUtil.getThreeAreaCode(areaCode));
            String url ="http://132.252.113.155:9999/api-gateway/cloudEndP2P/order/queryOrderDetail";//正式
            Map<String,String> map = new HashMap<>();
            String rsp = HttpClientUtils.sendPostWithHead(url, reqJson.toString(),false,map);
            JSONObject rspJson = JSON.parseObject(rsp);
            if("200".equals(rspJson.getString("responseCode"))){
                rspJson.put("resultCode", "0");
            }else{
                rspJson.put("resultCode", "01");//失败
            }
            response = Utils.builderResponse(rspJson.toString(), responseHead, responseJson, tranId,"resultCode","","msg");
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }finally{
            logger.debug("queryOrderDetail end");
        }
        return response.toString();
    }

    @Override
    public String queryResAbility(String request) {
//    	if(Utils.selectOldOrNewByAreaCode(request)){
        return queryResAbilityNew(request);
//    	}else{
//    		return queryResAbilityOld(request);
//    	}
    }

    @Override
    public String queryServiceNum(String requestJSON1) {
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            ReqInfo reqInfo = BeanUtil.toBean(requestJSON1,ReqInfo.class);
            JSONObject body = reqInfo.getBody();
            String appAccount = body.getString("appAccount");//智慧营维账号
            String msgCd ="ZW000001";//智恒内部的接口编码，代表查询的接口为  装维服务号码绑定关系查询接口
            String url ="http://132.228.172.231:29081";//正式
            JSONObject reqJson = new JSONObject();
            reqJson.put("appAccount", appAccount);
            reqJson.put("msgCd", msgCd);
            String rsp = HttpClientHelperForEop.postWithMNP(url, reqJson.toString());
            JSONObject rspJson = JSONObject.parseObject(rsp);
            if("200".equals(rspJson.getString("code"))){
                rspJson.put("resultCode", "0");
            }else{
                rspJson.put("resultCode", "01");//失败
            }
            response = Utils.builderResponse(rspJson.toString(), responseHead, responseJson, tranId,"resultCode","","msg");
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }finally{
            logger.debug("queryServiceNum end");
        }
        return response.toString();
    }

    @Override
    public String queryUserDevInfo(String requestJSON1) {
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            ReqInfo reqInfo = BeanUtil.toBean(requestJSON1,ReqInfo.class);
            JSONObject body = reqInfo.getBody();
            String accNbr = body.getString(Constants.ACC_NBR);//itv号
            JSONObject reqJson = new JSONObject();
            reqJson.put("itvAccount", accNbr);
            String url ="http://openapi.telecomjs.com:80/eop/ITVManagementSystem/queryUserDevInfo/queryUserDevInfo";//正式
            String rsp = HttpClientUtils.doPostJSONHttpsNewEOP(url, reqJson.toString());
            response = Utils.builderResponse(rsp, responseHead, responseJson, tranId,"rstCode","","rstMsg");//0 成功 10001输入参数不正确10002输入参数格式不正确10003权限不足10004API 不存在
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }finally{
            logger.debug("queryUserDevInfo end");
        }
        return response.toString();
    }

    @Override
    public String stampDect(String request) {
        logger.debug("印章识别 stampDect request:{}",request);
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            tranId = JSON.parseObject(request).getJSONObject("head").getString("tranId");
            ReqInfo reqInfo = BeanUtil.toBean(request,ReqInfo.class);
            JSONObject body = reqInfo.getBody();
            String base64string = body.getString("base64string");
            Boolean onlyDet = body.getBoolean("onlyDet");
            String type = body.getString("type");
            String url = "";
            if("pdf".equals(type)){
                url = "ttp://132.252.33.143:8559/ai/aiFactoryServer/v1/apis/1/stamp-dect:1.1@release.fixed/StampRec_service_pdf";
            }else{
                url = "http://132.252.33.143:8559/ai/aiFactoryServer/v1/apis/1/stamp-dect:1.1@release.fixed/StampRec_service";
            }

            JSONObject requestJSON = new JSONObject();
            requestJSON.put("base64string", base64string);
            if(null != onlyDet){
                requestJSON.put("OnlyDet", onlyDet);
            }

            String requestParam = requestJSON.toJSONString();
            logger.debug("印章识别 input: {}", requestParam);
            String result = HttpClientUtils.doPostJSONHttps(url, requestParam);
            logger.debug("印章识别  output: {}", result);

            if (!StringUtils.isEmpty(result)) {
                JSONObject resultJson = JSON.parseObject(result);
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, resultJson, "success", "00", responseJson);
            } else {
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, null, "内部接口返回空", "98", responseJson);
            }
            return response.toString();
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }
    }

    @Override
    public String startAutoCheck(String request) {
        logger.debug("NocBillImpl.startAutoCheck.request:{}",request);
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            JSONObject headJson = JSON.parseObject(request).getJSONObject("head");
            String areaCode = headJson.getString("areaCode");
            tranId = headJson.getString("tranId");
            ReqInfo reqInfo = BeanUtil.toBean(request,ReqInfo.class);
            JSONObject body = reqInfo.getBody();

            //天翼看家、全屋wifi dcoos地址
            String url = "http://jsjteop.telecomjs.com:8764/ida40/public/asip/webServiceTrans";

            JSONObject paramJson = new JSONObject();
            //方法名，传startAutoCheck即可
            paramJson.put("asipServiceName", "startAutoCheck");
            //专业类型，此处传“IDB_SA_20000”即可
            paramJson.put("businessCode", "IDB_SA_20000");
            //业务类型，此处传“IDB_SA_20000”即可
            paramJson.put("specialtyCode", "IDB_SA_20000");

            paramJson.put("faultCode", body.getString("accNbr"));
            paramJson.put("native_net_id", Utils.getNativeNetId(areaCode));
            //检测场景，全屋wifi：AIDEBUGGER_KF 天翼看家：tykjCheck_KF
            paramJson.put("opSrc", body.getString("opSrc"));

            logger.debug("NocBillImpl.startAutoCheck.paramJson={}",paramJson.toJSONString());
            String result = HttpClientHelperForEop.postWithMNP(url, paramJson.toString(),30000);
            logger.debug("NocBillImpl.startAutoCheck.result={}",result);
            if(!StringUtils.isBlank(result)) {
                JSONObject resultJson = JSON.parseObject(result);
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, resultJson, "success", "00", responseJson);
            }else{
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, null, "企信接口返回空", "01", responseJson);
            }
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }
        return response.toString();
    }

    @Override
    public String toIvrCheck(String request) {
        logger.debug("NocBillImpl.toIvrCheck.request:{}",request);
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            JSONObject headJson = JSON.parseObject(request).getJSONObject("head");
            tranId = headJson.getString("tranId");
            ReqInfo reqInfo = BeanUtil.toBean(request,ReqInfo.class);
            JSONObject body = reqInfo.getBody();

            //手机故障诊断接口地址
            String url = "http://jsjteop.telecomjs.com:8764/jsznycl/tool/toIvrCheck";

            JSONObject paramJson = new JSONObject();
            //手机号
            paramJson.put("accNum", body.getString("accNum"));

            logger.debug("NocBillImpl.toIvrCheck.paramJson={}",paramJson.toJSONString());
            String result = HttpClientHelperForEop.postWithMNP(url, paramJson.toString(),30000);
            logger.debug("NocBillImpl.toIvrCheck.result={}",result);
            if(!StringUtils.isBlank(result)) {
                JSONObject resultJson = JSON.parseObject(result);
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, resultJson, "success", "00", responseJson);
            }else{
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, null, "企信接口返回空", "01", responseJson);
            }
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }
        return response.toString();
    }

    @Override
    public String updateInvoiceInformation(String requestJson) {
        logger.debug("查询发票抬头信息updateInvoiceInformation.request:{}",requestJson);
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        //获取流水号
        String tranId ="";
        try {
            JSONObject headJson = JSON.parseObject(requestJson).getJSONObject("head");
            String areaCode = headJson.getString("areaCode");
            tranId = headJson.getString("tranId");
            ReqInfo reqInfo = BeanUtil.toBean(requestJson,ReqInfo.class);
            JSONObject body = reqInfo.getBody();

            //编号
            String id = body.getString("id");
            //本地网标识
            String lanId = StaticDataMappingUtil.getRegionByAreaCode(areaCode);

            JSONArray jsonArr = new JSONArray();
            JSONObject jsonObj = null;
            Set<Map.Entry<String, Object>> set = body.entrySet();
            for (Map.Entry<String, Object> entry : set) {
                String key = entry.getKey();
                String value = (String)entry.getValue();
                if(!"id".equals(key)){
                    jsonObj = new JSONObject();
                    jsonObj.put("op", "replace");
                    jsonObj.put("path", "/invoiceInformation/"+key);
                    jsonObj.put("value", value);
                    jsonArr.add(jsonObj);
                }
            }

            StringBuilder urlSb = new StringBuilder(BSSUrlConstants.INVOICE_INFORMATION_URL);
            urlSb.append("/").append(id);

            Map<String,String> headMap = new HashMap<>();
            headMap.put("X-CTG-Province-ID", "8320000");//省份Id
            headMap.put("X-CTG-Lan-ID", lanId);//地市id
            String requestId = UUID.randomUUID().toString();
            headMap.put(Constants.X_CTG_REQUEST_ID, requestId);
            String result = HttpClientHelperForEop.patchWithMNPWithHeader(urlSb.toString(), jsonArr.toString(),headMap);
            if(StringUtils.isBlank(result)) {
                Map<String,String> bodyMap = new HashMap<>();
                bodyMap.put(Constants.X_CTG_REQUEST_ID, requestId);
                response = BSSHelper.getErrInfo("02", "查询错误，集团返回空值!",bodyMap);
            }else{
                JSONObject resultJson = JSON.parseObject(result);
                resultJson.put(Constants.X_CTG_REQUEST_ID, requestId);
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, resultJson, "success", "00", responseJson);
            }
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }
        return response.toString();
    }

    @Override
    public String uploadOcrFtp(String request) {
        logger.debug("营业执照和单位授权书照片上传FTP request:{}",request);
        JSONObject response = null;
        RespInfo responseJson = new RespInfo();
        RespHead responseHead = new RespHead();
        responseJson.setHead(responseHead);
        StringBuilder remotePath = new StringBuilder("/home/cust/");
        //获取流水号
        String tranId ="";
        try (SFTPUtils sftp = new SFTPUtils(CUST_SFTP_IP, CUST_SFTP_PORT , CUST_SFTP_USER, CUST_SFTP_PD);){
            sftp.connect();
            tranId = JSON.parseObject(request).getJSONObject("head").getString("tranId");
            ReqInfo reqInfo = BeanUtil.toBean(request,ReqInfo.class);
            JSONObject body = reqInfo.getBody();
            String fileBase64 = body.getString("fileBase64");
            String fileName = body.getString("fileName");
            String ocrId = body.getString("ocrId");
            String phoneNumber = body.getString("phoneNumber");
            String taxNum = body.getString("taxNum");
            String type = body.getString("type");
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] bytes = decoder.decode(fileBase64);
            InputStream fileInputStream  = new ByteArrayInputStream(bytes);
            boolean flag = sftp.uploadFileByFileInputStream(remotePath.toString(), fileName, fileInputStream);
            if (flag) {
                UpOcrFtpInfo uofi = new UpOcrFtpInfo();
                uofi.setOcrId(ocrId);
                uofi.setPhoneNumber(phoneNumber);
                uofi.setTaxNum(taxNum);
                uofi.setType(type);
                uofi.setFileName(fileName);
                uofi.setRemoteFilePath(remotePath.toString());
                checkInfoMapper.insertUpOcrFtpInfo(uofi);
                JSONObject resultJson = new JSONObject();
                resultJson.put("ocrId", ocrId);
                resultJson.put("phoneNumber", phoneNumber);
                resultJson.put("taxNum", taxNum);
                resultJson.put("type", type);
                resultJson.put("fileName", fileName);
                resultJson.put("remoteFilePath", remotePath.toString());
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, resultJson, "success", "00", responseJson);
            } else {
                response = Utils.dealSuccessRespWithMsgAndStatus(responseHead, tranId, null, "内部接口返回空", "98", responseJson);
            }
            return response.toString();
        }catch(BaseAppException e){
            response = Utils.dealBaseAppExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        } catch (Exception e) {
            response = Utils.dealExceptionResp(responseHead, tranId, responseJson);
            return response.toString();
        }
    }

    public String queryResAbilityNew(String request) {
        JSONObject resultJson = new JSONObject();
        try {
            String params = java.net.URLDecoder.decode(request, "utf-8");
            logger.debug("queryResAbilityNew request:{}" , request);
            JSONObject json = JSON.parseObject(params);
            JSONObject jsonBody = (JSONObject) json.get("body");
            JSONObject jsonHead = json.getJSONObject("head");
            String nbrAccount = jsonBody.getString("nbrAccount");// 宽带账号
            String targetRate = jsonBody.getString("targetRate");// 提速目标速率
            String areaCode = jsonBody.getString("areaCode");// 区域编码

            // 宽带账号非空校验
            if (null == nbrAccount || "".equals(nbrAccount)) {
                JSONObject head = new JSONObject();
                JSONObject body = new JSONObject();
                body.put("TSR_RESULT", "1");
                body.put("TSR_MSG", "宽带账号不能为空!");
                resultJson.put("head", head);
                resultJson.put("body", body);
                return resultJson.toJSONString();
            }

            // 提速目标速率非空校验
            if (null == targetRate || "".equals(targetRate)) {
                JSONObject head = new JSONObject();
                JSONObject body = new JSONObject();
                body.put("TSR_RESULT", "1");
                body.put("TSR_MSG", "提速目标速率不能为空!");
                resultJson.put("head", head);
                resultJson.put("body", body);
                return resultJson.toJSONString();
            }

            // 区域编码非空校验
            if (null == areaCode || "".equals(areaCode)) {
                JSONObject head = new JSONObject();
                JSONObject body = new JSONObject();
                body.put("TSR_RESULT", "1");
                body.put("TSR_MSG", "区域编码不能为空!");
                resultJson.put("head", head);
                resultJson.put("body", body);
                return resultJson.toJSONString();
            }

            String url  = "http://jsjteop.telecomjs.com:8764/jseop/oss/O3Interface/wt/resAbilityCheck";
            JSONObject paramJson = new JSONObject();
            JSONObject msgHeadJson = new JSONObject();
            msgHeadJson.put("uuid", UUID.randomUUID().toString().replace("-", ""));
            msgHeadJson.put("sourceSystem", jsonHead.getString("channelId"));
            msgHeadJson.put("reqTime", DateUtils.getNOWDate());

            JSONObject msgBodyJson = new JSONObject();
            msgBodyJson.put("areaCode", areaCode);
            msgBodyJson.put("nbrAccount", nbrAccount);
            msgBodyJson.put("channeled", "1212121");
            msgBodyJson.put("targetRate", targetRate);

            JSONObject inputMessageJson = new JSONObject();
            inputMessageJson.put("msgHead", msgHeadJson);
            inputMessageJson.put("msgBody", msgBodyJson);
            paramJson.put("inputMessage", inputMessageJson);

            logger.debug("queryResAbilityNew paramJson:{}" , paramJson);
            String object = HttpClientHelperForEop.postToBill(url,paramJson.toString(), jsonHead.getString("areaCode"));
            logger.debug("queryResAbilityNew object:{}" , object);
            if (StringUtils.isEmpty(object)) {
                JSONObject head = new JSONObject();
                JSONObject body = new JSONObject();
                body.put("TSR_RESULT", "1");
                body.put("TSR_MSG", "调用接口失败，返回为空！");
                resultJson.put("head", head);
                resultJson.put("body", body);
                return resultJson.toJSONString();
            }

            JSONObject head = new JSONObject();
            JSONObject body = new JSONObject();
            body.put("TSR_RESULT", "0");
            body.put("TSR_MSG", object);
            resultJson.put("head", head);
            resultJson.put("body", body);

        } catch (Exception e) {
            JSONObject head = new JSONObject();
            JSONObject body = new JSONObject();
            body.put("TSR_RESULT", "1");
            body.put("TSR_MSG", "数据解析异常！请检查入参！");
            resultJson.put("head", head);
            resultJson.put("body", body);
            logger.error(e.getMessage());
            return resultJson.toJSONString();
        }
        return resultJson.toJSONString();
    }

    private JSONObject method1(String s){
        JSONObject json = new JSONObject();
        if ("0|||932100".equals(s)) {
            json.put("TSR_RESULT", "-1");
            json.put("TSR_CODE", "-1");
            json.put("Querylist", s);
        } else {
            String ss = s.substring(13, s.length());
            JSONArray ipAndPortArray = new JSONArray();
            if (-1 != ss.indexOf("***")) {
                // 接口返回存在多条，逐条遍历
                String[] stringSs = ss.split("\\*\\*\\*");
                for (int i = 0; i < stringSs.length; i++) {
                    method2(ss, ss, json,ipAndPortArray);
                }
            } else {
                method2(ss, ss, json,ipAndPortArray);
            }
            json.put("ipAndPortArray", ipAndPortArray);
            json.put("TSR_RESULT", "0");
            json.put("TSR_CODE", "0");
        }
        return json;
    }

    private void method2(String ss,String s,JSONObject json,JSONArray ipAndPortArray){
        // 接口返回一条
        JSONObject ipAndPortJson = new JSONObject();
        String[] stringArr = ss.split(":::");
        String username = stringArr[0];
//        String nasport = stringArr[1];
        String frameip = stringArr[3];
        String natframeip1 = stringArr[6];
        String natbeginport1 = stringArr[7];
        String ip = "";
        String port = "";
        if (!"null".equals(natframeip1)) {
            ip = natframeip1;
            port = natbeginport1;
        } else {
            ip = frameip;
            port = "1"; // 任意填写一个端口为用户端口（注意，范围为0-65535）
        }
        json.put("username", username);
        json.put("ip", ip);
        json.put("port", port);
        json.put("Querylist", s);
        ipAndPortJson.put("username", username);
        ipAndPortJson.put("ip", ip);
        ipAndPortJson.put("port", port);
        ipAndPortArray.add(ipAndPortJson);
    }
}
